<template>
  <div class="address-edit-box">
    <!-- 公用头部,通过 type 判断是新增还是编辑 -->
    <custom-header
      :title="`${type == 'add' ? '新增地址' : '编辑地址'}`"
    ></custom-header>
    <!-- 地址栏组件 -->
    <van-address-edit
      class="edit"
      :area-list="areaList"
      :address-info="addressInfo"
      :show-delete="type == 'edit'"
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>
  
<script>
import { reactive, onMounted, toRefs } from "vue";
import { Toast } from "vant";
import CustomHeader from 'components/CustomHeader.vue';
import { addAddress, getAddressDetail, EditAddress, DeleteAddress } from "service/address";
import { useRoute, useRouter } from "vue-router";

export default {
  components: {
    CustomHeader
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      // 省、市、区对象
      areaList: {
        province_list: {}, // 省份数据
        city_list: {}, // 市级别数据
        county_list: {}, // 县级别数据
      },
      searchResult: [],
      type: "add",
      addressId: '',
      addressInfo: {}
    });

    onMounted(() => {
      initData();
    });

    const initData = async () => {
      // 省市区列表构造
      let _province_list = {};
      let _city_list = {};
      let _county_list = {};

      window.tdist.getLev1().forEach((p) => {
        _province_list[p.id] = p.text;
        window.tdist.getLev2(p.id).forEach((c) => {
          _city_list[c.id] = c.text;
          window.tdist.getLev3(c.id).forEach((q) => {
            _county_list[q.id] = q.text;
          });
        });
      });

      // 使用上诉代码，组装好AddressEdit 所需的 area-list 数据后，赋值给相应的变量
      state.areaList.province_list = _province_list;
      state.areaList.city_list = _city_list;
      state.areaList.county_list = _county_list;

      const { type, addressId } = route.query;
      state.type = type;
      if(addressId && type == 'edit'){
        state.addressId = addressId
        addressDetail()
      }
    };

    const onSave = async (content) => {
      const params = {
        userName: content.name, // 收件人
        userPhone: content.tel, // 电话
        provinceName: content.province, // 省份名称
        cityName: content.city, // 市级名称
        regionName: content.county, // 区级名称
        detailAddress: content.addressDetail, // 详细地址
        defaultFlag: content.isDefault ? 1 : 0, // 是否为默认收货地址
      };
      if(state.type == 'edit'){
        params['addressId']  = state.addressId
      }
      //调用添加地址接口
      if(state.type == 'add'){
        await addAddress(params)
        Toast("新增地址成功");
      }else{
        await EditAddress(params)
        Toast("修改地址成功");
      }
    };

    const addressDetail = async () => {
        const { data: addressDetail } = await getAddressDetail(state.addressId)
        let _areaCode = ''
        const province = window.tdist.getLev1()
        Object.entries(state.areaList.county_list).forEach(([id, text]) => {
            // 先找出当前对应的区
            if (text == addressDetail.regionName) {
                // 找到区对应的几个省份
                const provinceIndex = province.findIndex(item => item.id.substr(0, 2) == id.substr(0, 2))
                // 找到区对应的几个市区
                // eslint-disable-next-line no-unused-vars
                const cityItem = Object.entries(state.areaList.city_list).filter(([cityId, cityName]) => cityId.substr(0, 4) == id.substr(0, 4))[0]
                // 对比找到的省份和接口返回的省份是否相等，因为有一些区会重名
                if (province[provinceIndex].text == addressDetail.provinceName && cityItem[1] == addressDetail.cityName) {
                    _areaCode = id
                }
            }
        })
        state.addressInfo = {
            id: addressDetail.addressId,
            name: addressDetail.userName,
            tel: addressDetail.userPhone,
            province: addressDetail.provinceName,
            city: addressDetail.cityName,
            county: addressDetail.regionName,
            addressDetail: addressDetail.detailAddress,
            areaCode: _areaCode,
            isDefault: !!addressDetail.defaultFlag
        }
    }

    const onDelete = async () => {
        await DeleteAddress(state.addressId)
        Toast('删除成功')
        setTimeout(() => {
            router.back()
        }, 1000)
    }

    return {
      ...toRefs(state),
      onSave,
      onDelete,
    };
  },
};
</script>
  <style lang="less">
@import "../theme/custom.less";
.edit {
  .van-field__body {
    textarea {
      height: 26px !important;
    }
  }
}
.address-edit-box {
  .van-address-edit {
    .van-button--danger {
      background: @primary;
      border-color: @primary;
    }
    .van-switch--on {
      background: @primary;
    }
  }
}
</style>